package recovery

import (
	"fmt"
	recoveryInterface "go-toy/middleware/recovery/interf"
	"go-toy/util"
	"log"
	"os"
	"runtime/debug"

	"github.com/gin-gonic/gin"
)

type Simple struct {
}

func (g *Simple) Handle() gin.HandlerFunc {
	return func(c *gin.Context) {

		defer func() {
			if r := recover(); r != nil {

				errorlogPath := util.Viper.GetString("errorLog.path")

				file, err := os.OpenFile(errorlogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
				if err != nil {
					fmt.Printf("error: unable to open log file: %v\n", err)
				}
				defer file.Close()

				log.SetOutput(file)

				// print stack trace to log file
				stackTrace := debug.Stack()
				log.Printf("captured panic: %v\nstack trace:\n%s\n\n", r, stackTrace)

				c.JSON(
					200,
					r,
				)
			}
		}()

		c.Next()
	}
}

var SimpleIntance recoveryInterface.Recovery = &Simple{}
